import { hash } from 'ohash'

// 后端返回的数据类型
export interface ResOptions<T> {
  data: T
  status?: number
  message?: string
}

class Http {
  /**
   * api请求封装
   * @param { String } url 请求地址
   * @param { Object } options useFtech第二个参数
   */
  async fetch(url: string, options?: object) {
    try {
      // Nuxt3.0正式版环境变量要从useRuntimeConfig里的public拿
      const {
        public: { VITE_APP_API_URL }
      } = useRuntimeConfig()
      const reqUrl = VITE_APP_API_URL + url // 你的接口地址
      // 设置key
      const key = hash(options + url)

      const { data } = await useFetch(reqUrl, {
        ...options,
        key
      })
      const result = JSON.parse(data.value as string) as ResOptions<any>
      const { status, message } = result
      if (status !== 1) {
        // 这里处理错你自定义的错误，例如 status !== 1
        throw createError({
          statusCode: 500,
          statusMessage: reqUrl,
          message: message || '服务器内部错误'
        })
      } else {
        return result.data // 这里直接返回data
      }
    } catch (err) {
      console.log(err)
      return Promise.reject(err)
    }
  }

  get(url: string, params?: any) {
    return this.fetch(url, { method: 'get', params })
  }

  post(url: string, body?: any) {
    return this.fetch(url, { method: 'post', body })
  }

  put(url: string, body?: any) {
    return this.fetch(url, { method: 'put', body })
  }

  delete(url: string, body?: any) {
    return fetch(url, { method: 'delete', body })
  }
}

export default Http
